<template>
  <div class="card">
    <div class="card-header">
      <h3 class="card-title">{{ title }}</h3>
    </div>
    <div class="card-body">
      <div class="chart-container" style="position: relative; height: 300px;">
        <canvas ref="chartCanvas"></canvas>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUpdated, watch } from 'vue'
import Chart from 'chart.js/auto'

export default {
  name: 'ChartCard',
  props: {
    title: {
      type: String,
      required: true
    },
    chartData: {
      type: Object,
      required: true
    },
    chartType: {
      type: String,
      default: 'line'
    }
  },
  setup(props) {
    const chartCanvas = ref(null)
    let chartInstance = null

    const initChart = () => {
      if (chartInstance) {
        chartInstance.destroy()
      }

      const ctx = chartCanvas.value.getContext('2d')
      chartInstance = new Chart(ctx, {
        type: props.chartType,
        data: props.chartData,
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'top',
            },
            tooltip: {
              mode: 'index',
              intersect: false,
            }
          },
          scales: {
            x: {
              grid: {
                display: false
              }
            },
            y: {
              beginAtZero: true
            }
          },
          animation: {
            duration: 1000,
            easing: 'easeOutQuart'
          }
        }
      })
    }

    onMounted(() => {
      initChart()
    })

    watch(() => props.chartData, () => {
      initChart()
    }, { deep: true })

    return {
      chartCanvas
    }
  }
}
</script>    